//
//  News.swift
//  XFRequestDemo
//
//  Created by 雪飞 on 2021/10/28.
//

import SwiftUI
import XFRequest
import KakaJSON

struct News: View {
    @State var type: newstype
    @State var newsdata:[[String:String]] = []
    @State var models:[NewsData] = []
    var title:String{
        type == .Default ? "推荐" : type == .Needed ? "体育" : "娱乐"
    }
    var body: some View {
        VStack{
            if type == .Default || type == .Needed{
                List(newsdata, id: \.self){data in
                    LazyVStack(alignment: .leading) {
                        Text("\(data["title"] ?? "")")
                    }
                }
            }else{
                List(models){model in
                    LazyVStack(alignment: .leading) {
                        Text(model.title)
                    }
                }
            }
        }
        .navigationTitle("新闻列表-\(title)")
        .navigationBarTitleDisplayMode(.inline)
        .onAppear(){
            getnews()
        }
    }
    
    ///  获取新闻数据
    func getnews() {
        let result =  XF.request(newsapi.newslist(type: type))
        if type == .Default{
            result.defaultSuccess { json in
                // 自己对返回数据进行判断处理
                if let dic = json as? [String:Any]{
                    if dic["error_code"] as! Int == 0{
                        let resultDic:[String:Any] = dic["result"] as! [String:Any]
                        newsdata = resultDic["data"] as! [[String:String]]
                    }else{
                        print("失败")
                    }
                }
            }
        }else if type == .Needed{
            // 返回需要的数据
            result.success { data in
                if let dic = data as? [String:Any]{
                    newsdata = dic["data"] as! [[String : String]]
                }
            }
        }else{
            // 返回model
            result.successModel(ctype: NewsModel.self) { nmodel, nmodels in
                models = nmodel!.data
            }
        }
    }
    
    
}


/// 自定义扩展
extension XFResult{
    /// 不使用KakaJSON    自定义
    func mymodel(success:@escaping (Any) -> Void) -> XFResult {
        self.success { data in
            let test = data // 将data转为model
            success(test) // 闭包回调
        }
    }
    /// 自定义成功失败
    func requestResult(success:@escaping (Any) -> Void,error:@escaping (Any) -> Void) -> XFResult {
        self.defaultSuccess { data in
            // 对数据进行判断处理
            // 成功 success()
            // 失败 error（）
        }
    }
}


struct NewsModel:Identifiable,Codable,Convertible{
    var id = UUID().uuidString
    var stat: Int = 0
    var pageSize: Int = 0
    var data = [NewsData]()
    var page: Int = 0
}

struct NewsData:Identifiable,Codable,Convertible {
    var id = UUID().uuidString
    var category: String = ""
    var thumbnailPicS02: String = ""
    var url: String = ""
    var authorName: String = ""
    var date: String = ""
    var isContent: String = ""
    var thumbnailPicS03: String = ""
    var uniquekey: String = ""
    var title: String = ""
    var thumbnailPicS: String = ""
}

struct News_Previews: PreviewProvider {
    static var previews: some View {
        News(type: .Default)
    }
}
